import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Table, Button, Space, Tag, Popconfirm, message, Modal, Form, Input, Switch } from 'antd';
import { ArrowLeftOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { contestService } from '@/services/contestService';
import { Announcement } from '@/types/contest';
import styles from './Announcements.module.css';
import dayjs from 'dayjs';
import MDEditor from '@/components/MDEditor';

const AnnouncementManagement: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingAnnouncement, setEditingAnnouncement] = useState<Announcement | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    if (id) {
      fetchAnnouncements();
    }
  }, [id]);

  const fetchAnnouncements = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const response = await contestService.getAnnouncements({ contest_id: Number(id) });
      setAnnouncements(response.data.data || []);
    } catch (error) {
      message.error('获取比赛公告失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (announcementId: number) => {
    try {
      await contestService.deleteAnnouncement(announcementId);
      message.success('删除成功');
      fetchAnnouncements();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleEdit = (announcement: Announcement) => {
    setEditingAnnouncement(announcement);
    form.setFieldsValue({
      title: announcement.title,
      content: announcement.content,
      visible: announcement.visible
    });
    setModalVisible(true);
  };

  const handleAdd = () => {
    setEditingAnnouncement(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      await form.validateFields();
      const values = form.getFieldsValue();
      
      if (editingAnnouncement) {
        await contestService.updateAnnouncement(editingAnnouncement.id, {
          ...values,
          contest: Number(id)
        });
        message.success('更新成功');
      } else {
        await contestService.createAnnouncement({
          ...values,
          contest: Number(id)
        });
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchAnnouncements();
    } catch (error: any) {
      if (!error.response) {
        // Form validation error, do nothing
      } else {
        message.error(editingAnnouncement ? '更新失败' : '创建失败');
      }
    }
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '可见性',
      dataIndex: 'visible',
      key: 'visible',
      render: (visible: boolean) => (
        <Tag color={visible ? 'green' : 'red'}>
          {visible ? '可见' : '隐藏'}
        </Tag>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '发布者',
      dataIndex: 'created_by',
      key: 'created_by',
      render: (created_by: { username: string }) => created_by.username,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Announcement) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个公告吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => navigate(`/contest/${id}`)}
        >
          返回比赛详情
        </Button>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          添加公告
        </Button>
      </div>

      <Card title="比赛公告管理">
        <Table
          columns={columns}
          dataSource={announcements}
          rowKey="id"
          loading={loading}
          expandable={{
            expandedRowRender: (record) => (
              <div dangerouslySetInnerHTML={{ __html: record.content }} />
            ),
          }}
        />
      </Card>

      <Modal
        title={editingAnnouncement ? '编辑公告' : '添加公告'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label="公告标题"
            rules={[{ required: true, message: '请输入公告标题' }]}
          >
            <Input placeholder="请输入公告标题" />
          </Form.Item>
          <Form.Item
            name="content"
            label="公告内容"
            rules={[{ required: true, message: '请输入公告内容' }]}
          >
            <MDEditor />
          </Form.Item>
          <Form.Item
            name="visible"
            label="是否可见"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AnnouncementManagement; 